package com.novel.resource.cos.autoConfigurer;

import com.novel.resource.cos.config.CosConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

/**
 * cos 客户端工厂
 *
 * @author novel
 * @date 2020/1/2
 */
@Slf4j
public class CosClientFactoryBean implements FactoryBean<COSClient>, InitializingBean, DisposableBean {
    private COSClient cosClient;
    private CosConfig cosConfig;

    public CosClientFactoryBean(CosConfig cosConfig) {
        this.cosConfig = cosConfig;
    }

    @Override
    public COSClient getObject() throws Exception {
        return this.cosClient;
    }

    @Override
    public Class<?> getObjectType() {
        return COSClient.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void destroy() throws Exception {
        if (this.cosClient != null) {
            this.cosClient.shutdown();
            log.info("COSClient 销毁...");
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        COSCredentials cred = new BasicCOSCredentials(cosConfig.getSecretId(), cosConfig.getSecretKey());
        // 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region(cosConfig.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        log.info("COSClient 初始化...");
        cosClient = new COSClient(cred, clientConfig);
        if (!cosClient.doesBucketExist(cosConfig.getBucketName())) {
            cosClient.createBucket(cosConfig.getBucketName());
        }
    }
}
